package com.sc.admin.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sc.admin.mapper.MenuMapper;
import com.sc.admin.pojo.Menu;

@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private MenuMapper menuMapper;

	@Override
	public Menu getMenuById(int id) {
		return menuMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Menu> getMenusByPid(int pid) {
		return menuMapper.selectMenusByPid(pid);
	}

	@Override
	public void add(Menu menu) {
		menuMapper.insertSelective(menu);
		// 修改父菜单的isParent为true
		int pid = menu.getPid();
		menu = new Menu();
		menu.setId(pid);
		menu.setIsParent(true);
		menuMapper.updateByPrimaryKeySelective(menu);
	}

	@Override
	public Menu checkName(String name) {
		return menuMapper.selectMenuByName(name);
	}

	@Override
	public void update(Menu menu) {
		menuMapper.updateByPrimaryKeySelective(menu);
	}

	//递归删除
	@Override
	public void delete(int id) {
		// 先查询
		Menu menu = menuMapper.selectByPrimaryKey(id);
		if (menu.getIsParent()) {
			List<Menu> children = menuMapper.selectMenusByPid(id);
			for (Menu m : children) {
				delete(m.getId());
			}
			menuMapper.deleteByPrimaryKey(id);
		} else {
			menuMapper.deleteByPrimaryKey(id);
		}
	}
	
	//递归查询
	@Override
	public List<Menu> getSyncChildrenByPid(int pid) {
		// 先查一级
		List<Menu> menus = menuMapper.selectMenusByPid(pid);
		for (Menu menu : menus) {
			if (menu.getIsParent()) {
				List<Menu> children = getSyncChildrenByPid(menu.getId());
				menu.setChildren(children);
			}
		}
		return menus;
	}

}
